package web;

import dao.FileDao;
import entity.UpFile;
import utils.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/list")
public class ListFile extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        HttpSession session = req.getSession();
        Object loginUser = session.getAttribute(Constant.LOGIN_SESSION);
        if (loginUser == null) {
            resp.getWriter().write("<h3 style='color:red'>请先登录</h3>");
            return;
        }
        // 获取上传的文件夹中的所有列表并渲染到客户端
        try {
            List<UpFile> files = FileDao.selectALl();
            resp.getWriter().write(getHtml(files));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        // 渲染

    }

    private static String getHtml(List<UpFile> files) {
        StringBuilder html = null;
        if (files != null) {
            html = new StringBuilder("<h1 style='color:red'>欢迎来到开发喵资源网</h1><style>table, tr,td{border:1px solid black;}</style>");
            html.append("<table>" + "<tr>"
                    + "<td>id</td>"
                    + "<td>文件名</td>"
                    + "<td>文件大小</td>"
                    + "<td>创建时间</td>"
                    + "<td>上传IP</td>"
                    + "<td>下载地址</td>"
                    + "<td>是否下载文件</td>"
                    + "</tr>");
            for (UpFile file: files) {
                html.append("<tr>" + "<td>")
                        .append(file.getId()).append("</td>").append("<td>")
                        .append(file.getName()).append("</td>").append("<td>")
                        .append(file.getSize()).append("</td>").append("<td>")
                        .append(file.getCreat_time()).append("</td>").append("<td>")
                        .append(file.getUpload_ip()).append("</td>").append("<td>")
                        .append(file.getDownload_link()).append("</td>").append("<td>")
                        .append("<a href=").append(file.getDownload_link()).append(">下载文件</a>").append("</td>")
                        .append("<tr>");
            }
            html.append("</table>");
        }
        return html.toString();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
